from functools import wraps

from django.core.cache import cache

from utils.mixins.common_mixins.logger import common_logger


def cache_key_decorator(key, expire=60):
    """
    设置缓存装饰器
    :param key: 缓存key值
    :param expire: 缓存超时时间, 秒
    """

    def set_func(func):
        @wraps(func)
        def call_func(*args, **kwargs):

            try:
                value = cache.get(key, None)
            except Exception as e:
                common_logger.error(f'读取缓存失败, 从原方法获取, func: {func}, error: {e}')
            else:
                if value is not None:
                    common_logger.info(f'获取cache: {key}, 获取成功, 直接return')
                    return value

            common_logger.info(f'获取cache: {key}, 缓存失效, 从原方法获取, func: {func}')
            ret = func(*args, **kwargs)

            try:
                common_logger.info(f'设置缓存, key: {key}')
                if len(ret) > 0:
                    cache.set(key, ret, expire)
            except Exception as e:
                common_logger.error(f'设置缓存失败, key: {key}, error: {e}')
            else:
                if len(ret) > 0:
                    common_logger.info(f'设置缓存成功, key: {key}')
                else:
                    common_logger.info('未获取到数据,不设置缓存')

            return ret

        return call_func

    return set_func


def cache_delete_decorator(key):
    """
    删除缓存装饰器, 通常用于更新数据时
    :param key: 缓存key值
    """

    def set_func(func):
        @wraps(func)
        def call_func(*args, **kwargs):
            ret = func(*args, **kwargs)
            try:
                cache.delete(key)
            except Exception as e:
                common_logger.error(f'删除缓存失败, key: {key}, error: {e}')
            else:
                common_logger.info(f'删除缓存成功, key: {key}')
            return ret

        return call_func

    return set_func
